package com.xyz.viewpractice;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class OnTouchScrollView extends View {

    private int lastX;
    private int lastY;
    private int width;
    private int height;

    public OnTouchScrollView(Context context) {
        super(context);
    }

    public OnTouchScrollView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public OnTouchScrollView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = getMeasuredWidth();
        height = getMeasuredHeight();
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - lastX;
                int deltaY = y - lastY;
                if (Math.abs(deltaX) > 10 || Math.abs(deltaY) > 10) {
                    //这个时候 才可以称之为拖动
                    int left = getLeft() + deltaX;
                    int top = getTop() + deltaY;
                    int right = left + width;
                    int bottom = top + height;
                    this.layout(left, top, right, bottom);
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
            default:
                break;
        }
        lastX = x;
        lastY = y;
        return true;
    }
}
